package com.shzq.controller;

import com.shzq.pojo.ResultDTO;
import com.shzq.pojo.UserDO;
import com.shzq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zml
 * time: 2020/5/7 16:07
 * mailbox  zmlelselove@126.com
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public ResultDTO register(@RequestBody UserDO user){
        try {
            userService.add(user);
            return new ResultDTO("注册成功", "success");
        }catch (Exception e){
            e.printStackTrace();
            return new ResultDTO("注册失败","warning");
        }
    }

    @RequestMapping("/login")
    public ResultDTO login(@RequestBody UserDO user, HttpServletResponse response){
        String username = user.getUsername();
        if(username==null) {
            return new ResultDTO("登陆失败", "warning");
        }
        UserDO dataUser = userService.getByUsername(username);
        if(dataUser==null){
            return new ResultDTO("登陆失败", "warning");
        }
        String password = dataUser.getPassword();
        boolean correct = BCrypt.checkpw(user.getPassword(), password);
        if(correct){
            Cookie cookie = new Cookie("uid", username);
            cookie.setMaxAge(-1);
            cookie.setPath("/");
            cookie.setDomain("localhost");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return new ResultDTO("登陆成功", "success");
        }
        return new ResultDTO("登陆失败", "warning");
    }
}
